package cn.xlbweb.cli.shiro;

import cn.xlbweb.cli.common.ResponseCode;
import cn.xlbweb.cli.common.ServerResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: bobi
 * @date: 2019-09-16 20:21
 * @description:
 */
@Slf4j
public class CliAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 放行OPTIONS请求
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 获取requestURI
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestURI = httpServletRequest.getRequestURI();
        log.error("{}请求被拒绝，token验证失败", requestURI);
        // 自定义返回信息
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServerResponse serverResponse = ServerResponse.error(ResponseCode.UN_LOGIN.getCode(), ResponseCode.UN_LOGIN.getMessage());
        // todo 这样返回不会过滤掉isSuccess字段
        httpServletResponse.getWriter().write(JSON.toJSONString(serverResponse));
        return false;
    }
}
